package com.example.analyzevisio.utis;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import java.io.*;

import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class anaiyvisio {
    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com"; // 替换为你的OSS区域Endpoint
    private static String accessKeyId = "LTAI5tF7dZviZsFeAVwM79kN"; // 替换为你的AccessKey ID
    private static String accessKeySecret = "jxARbK0SOp0OYyAk8XxGtOzSLLYBP1"; // 替换为你的AccessKey Secret
    private static String bucketName = "mengshuai-test"; // 替换为你的Bucket名称
//    private static String objectName = "绘图1.vsdx"; // 替换为你的文件名
/*    public static void main(String[] args) {
        String fileZip = "C:\\Users\\ms206\\Desktop\\visio图\\绘图2.vsdx";
        String outputFolder = "C:\\Users\\ms206\\Desktop\\visio图\\代码解压\\";
        unzip(fileZip,outputFolder);
    }*/
    public static void unzip(String objectName, String destDir) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //阿里
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);


        File dir = new File(destDir);
        if (!dir.exists()) dir.mkdirs();
        byte[] buffer = new byte[1024];
        //使用本地
//        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(objectName))) {
        //使用oss
        try (ZipInputStream zis = new ZipInputStream(ossObject.getObjectContent())) {

            ZipEntry zipEntry = zis.getNextEntry();
            while (zipEntry != null) {
                File newFile = newFile(dir, zipEntry);
                if (zipEntry.isDirectory()) {
                    newFile.mkdirs();
                } else {
                    // fix for Windows-created archives
                    File parent = newFile.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                zipEntry = zis.getNextEntry();
            }
            zis.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {
        File destFile = new File(destinationDir, zipEntry.getName());

        String destDirPath = destinationDir.getCanonicalPath();
        String destFilePath = destFile.getCanonicalPath();

        if (!destFilePath.startsWith(destDirPath + File.separator)) {
            throw new IOException("Entry is outside of the target dir: " + zipEntry.getName());
        }

        return destFile;
    }
}
